package on;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Transient;


@Entity
public class Salto implements Comparable<Salto>{
	
	public static String BUFFER_DEBUG = "";
	
	
	@Transient
	private Link link;
	
	@ManyToMany(cascade=CascadeType.ALL)
	private Set<LightLink> lightlinks = new TreeSet<LightLink>();
	
	private int secuencia;
	
	@Id
	@GeneratedValue
	private long id;
	
	public Salto(){}
	
	public Salto(int secuencia, Link c){
		this.link = c;
		this.secuencia = secuencia;
	}
	
	public int getSecuencia() {
		return secuencia;
	}
	public void setSecuencia(int secuencia) {
		this.secuencia = secuencia;
	}
	
	@Override
	public int hashCode() {
		return link.hashCode()*100 + secuencia;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (! (obj instanceof Salto)) return false;
		
		Salto b = (Salto) obj;
		
		return this.hashCode() == b.hashCode();
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public Link getLink() {
		return link;
	}
	
	public Nodo getSource(){
		return link.getSource();
	}
	
	public Nodo getDestination(){
		return link.getDestination();
	}

	public void setLink(Link c) {
		this.link = c;
		this.lightlinks.clear();
	}

	public Set<LightLink> getLightLinks() {
		return lightlinks;
	}

	public void setLightLinks(Set<LightLink> lightlinks) {
		this.lightlinks = lightlinks;
	}
	
	@Override
	public int compareTo(Salto b) {
		return this.secuencia - b.secuencia;
	}

	public void definirEnlace(LightLink [] e, long sid){
		
		BUFFER_DEBUG = link + "posee capacidad para " + e.length + " lightlinks: " + link.poseeCapacidad(e.length);
		
		for (int k = 0; k < e.length; k++){
			if ( e[k] == null ) {
				if( k == 0 ){
					e[k] = link.getLightLinkLibre();
				} else {
					e[k] = e[k-1].next();
				}
			} else {
				e[k] = link.getLightLinkLibre(e[k]);
			}
			
			if ( e[k] == null ) System.out.println("no se puede obtener un lightlink en " + link);
			
			link.getDestination().receive(e[k]);
			link.getSource().transmit(e[k]);
			
			lightlinks.add(e[k]);
			
			e[k].bloquear();
			e[k].setLightPathID(sid + k);
			
		}
	}
	
	public void desbloquearLightLinks(){
		for( LightLink l : lightlinks ){
			l.desbloquear();
			l.setLightPathID(-1);
		}
	}
	
	@Override
	public String toString() {
		return "("+secuencia+","+link+")";
	}
}
